package com.epoint.mobileoa.tools;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.widget.Toast;

/**
 * 附件下载
 * @author liyc
 */
public class GetRemoteInfo extends AsyncTask<String, String, String> {

	public static final int DIALOG_DOWNLOAD_PROGRESS = 0;

	Activity con;
	String attachfilepath;
	ProgressDialog mProgressDialog;
	public GetRemoteInfo(Activity con,String attachfilepath,ProgressDialog mProgressDialog){
		this.con = con;
		this.attachfilepath = attachfilepath;
		this.mProgressDialog = mProgressDialog;
	}

	URLConnection conexion ;
	int lenghtOfFile;
	public void executeBefore(final String...aurl){
		URL url;
		String urlnew;
		try {
			urlnew = new String(aurl[0].getBytes("utf-8"),"ISO-8859-1");
			urlnew  = urlnew.replaceAll(" ","%20");
			url = new URL(urlnew);

			conexion = url.openConnection();
			lenghtOfFile = conexion.getContentLength();
			File file = new File(attachfilepath);

			if(file.exists()&&file.length()==lenghtOfFile){
				Builder dlg = new AlertDialog.Builder(con)
				.setTitle("提示")
				.setMessage("软件已经下载，要打开吗？")
				.setPositiveButton("直接打开", // 设置"确定"按钮
						new DialogInterface.OnClickListener() // 设置事件监听
				{
					public void onClick(DialogInterface dialog,
							int whichButton) {
						Intent intent = new Intent(Intent.ACTION_VIEW); 
						intent.setDataAndType(Uri.fromFile(new File(attachfilepath)), "application/vnd.android.package-archive"); 
						con.startActivity(intent); 
					}
				})
				.setNegativeButton("重新下载",
						new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog,
							int which) {
						downTip(aurl);
					}

				});
				showDialog(dlg);
			}
			else{
				downTip(aurl);
			}
		} catch (UnsupportedEncodingException e) {
			Toast.makeText(con, e.getMessage(), 1000).show();
		} catch (MalformedURLException e) {
			Toast.makeText(con, e.getMessage(), 1000).show();
		} catch (IOException e) {
			Toast.makeText(con, e.getMessage(), 1000).show();
		}
	}

	void downTip(final String...aurl){
		long kblength = (long)lenghtOfFile/1024;
		if(kblength>4096){
			Builder dlg = new AlertDialog.Builder(con)
			.setTitle("提示")
			.setMessage("该附件大小超过4M，可能将花费您较多网络流量，继续下载吗？")
			.setPositiveButton("确定", // 设置"确定"按钮
					new DialogInterface.OnClickListener() // 设置事件监听
			{
				public void onClick(DialogInterface dialog,
						int whichButton) {
					execute(aurl);
				}
			})
			.setNegativeButton("取消",
					new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog,
						int which) {

				}

			})
			;
			showDialog(dlg);
		}
		else{
			execute(aurl);
		}
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		onCreateDialog(DIALOG_DOWNLOAD_PROGRESS);
	}

	@Override
	protected String doInBackground(final String... aurl) {
		try {
			int count;
			InputStream input = conexion.getInputStream();
			OutputStream output = new FileOutputStream(attachfilepath);
			byte data[] = new byte[1024];
			long total = 0;
			while ((count = input.read(data)) != -1) {
				total += count;
				publishProgress("" + (int) ((total * 100) / lenghtOfFile));
				output.write(data, 0, count);
			}
			output.flush();
			output.close();
			input.close();

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		return null;
	}

	Handler handler = new Handler();
	public void showDialog(final Builder dlg) {
		handler.post(new Runnable() {
			@Override
			public void run() {
				dlg.create().show();
			}
		});
	}

	protected Dialog onCreateDialog(int id){
		switch (id) {
		case DIALOG_DOWNLOAD_PROGRESS:
			mProgressDialog = new ProgressDialog(con);
			mProgressDialog.setMessage("正在下载更新软件...");
			mProgressDialog.setButton("取消",new mpdListener());
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgressDialog.setCancelable(true);
			mProgressDialog.show();
			return mProgressDialog;
		default:
			return null;
		}
	}
	boolean cancelflag = false;
	class mpdListener implements OnClickListener{

		@Override
		public void onClick(DialogInterface paramDialogInterface, int paramInt) {
			cancelflag = true;
			cancel(true);
			deleteFile(attachfilepath);
		}

	}

	protected void onProgressUpdate(String... progress) {
		mProgressDialog.setProgress(Integer.parseInt(progress[0]));
	}

	@Override
	protected void onPostExecute(String unused) {
		mProgressDialog.dismiss();
		openFile();
	}

	public void openFile(){
		File file = new File(attachfilepath);
		if(cancelflag){
			if(file.exists()){
				file.delete();
			}
		}
		else{
			if(file.exists()){
				Builder dlg = new AlertDialog.Builder(con).setTitle("提示")
						.setMessage("下载完毕，立即安装吗？")
						.setPositiveButton("确定", new OnClickListener() {

							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								/*Uri packageURI = Uri.parse("package:com.epoint.mobileoa.view");      
								Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);      
								con.startActivity(uninstallIntent);*/
								
								
								Intent intent = new Intent(Intent.ACTION_VIEW); 
								intent.setDataAndType(Uri.fromFile(new File(attachfilepath)), "application/vnd.android.package-archive"); 
								con.startActivity(intent); 
								
							}
						})
						.setNegativeButton("取消", null)
						;
				dlg.create().show();
			}
			else{
				//			Toast.makeText(con, "文件下载出错", 1000).show();
			}
		}
		cancelflag = false;
	}

	@Override
	protected void onCancelled() {
		super.onCancelled();
	}

	public void WriteText(Context context, String fileName, String data) {
		FileOutputStream fOut = null;
		OutputStreamWriter osw = null;
		try {
			fOut = context.openFileOutput(fileName, 1);
			osw = new OutputStreamWriter(fOut);
			osw.write(data);
			osw.flush();
			Toast.makeText(context, "附件已经保存！", Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(context, "附件保存出错！", Toast.LENGTH_SHORT).show();
		} finally {
			try {
				osw.close();
				fOut.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void deleteFile(String path){
		File file = new File(path);
		if(cancelflag){
			if(file.exists()){
				file.delete();
			}
		}
	}
}


